<!-- src/views/system/user/index.vue -->
<template>
    <div class="tech-blue-container">
        <div class="map-header">
            <h2 class="map-title">应急管理系统</h2>
            <h2 class="map-title" v-if="currentChooseWorkInfo.workNo">当前选中的事件编号{{ currentChooseWorkInfo.workNo }}</h2>
            <button class="fullscreen-btn" @click="toggleFullscreen">
                <span v-if="!isFullscreen">全屏</span>
                <span v-else>退出全屏</span>
            </button>
        </div>

        <!-- 添加科技感loading -->
        <div v-if="loading" class="tech-loading">
            <div class="loading-content">
                <div class="loading-spinner" />
                <div class="loading-text">正在加载地图...</div>
            </div>
        </div>

        <div class="map-container">
            <div id="map" class="tech-map" :class="{ 'map-hidden': loading }" />
            <div class="left-info">
                <button v-if="drawerVisible == false" class="style-btn" @click="toggleDrawer">事件信息</button>
                <DrawerPanel
                    ref="DrawerPanel"
                    @updateLocationView="updateLocationViewData"
                    :visible.sync="drawerVisible"
                    @updatePersonnelHistory="updatePersonnelHistory"
                    @updateRightInfo="updateRightInfo"
                    @currentInfo="updateCurrentInfo"
                />
            </div>
            <div class="right-info">
                <button v-if="drawerRightVisible == false" class="style-btn" @click="drawerRightVisibleChange">设备信息</button>
                <DrawerPanelRight
                    @updateLocationView="updateLocationViewData"
                    :trainListParams="trainListParams"
                    :getWorkEquLists="getWorkEquLists"
                    :currentChooseWorkUserList="currentChooseWorkUserList"
                    :visible.sync="drawerRightVisible"
                />
            </div>
        </div>

        <!-- 添加车辆标记组件 -->
        <CarMarkers
            v-if="map"
            ref="carMarkers"
            :map="map"
            :car-list="carList"
            :car-window="carWindow"
            :car-window-content="carWindowContent"
            @updateCarWindow="carWindowContent = $event"
            @drawComplete="handleCarDrawComplete"
        />

        <!-- 添加人员标记组件 -->
        <WorkerMarkers v-if="map" ref="workerMarkers" :map="map" :personnel-history-list="personnelHistoryList" />

        <!-- 添加人员轨迹组件 -->
        <PersonTrackLine v-if="map && personTrackData" ref="personTrackLine" :map="map" :track-data="personTrackData" />
    </div>
</template>

<script>
import WorkerMarkers from "./WorkerMarkers.vue";
import PersonTrackLine from "./PersonTrackLine.vue";
import CarMarkers from "./CarMarkers.vue";
import DrawerPanel from "./DrawerPanel.vue";
import DrawerPanelRight from "./DrawerPanelRight.vue";
import WebSocketService from "@/utils/websocket.js"; // 引入WebSocket服务
import {
    tbLocationTrainList,
    TbEquTrainList,
    getWorkEquList,
    getWorkOrderList,
    getLocationQuertz,
    getWorkOrderUserByWorkNo, //根据任务编号获取人员信息
    getTbWorkOrderUserList, //初始化获取所有作业人员信息
} from "@/api/bussiness/bussiness"; // 引入车辆位置接口

export default {
    name: "TodoMap",
    components: {
        WorkerMarkers,
        PersonTrackLine,
        CarMarkers,
        DrawerPanel,
        DrawerPanelRight,
    },
    data() {
        return {
            /**
             * 自定义右侧数据信息start
             */
            currentChooseWorkInfo: {},
            currentChooseWorkUserList: [], //当前选中事件用户i二标
            /**
             * 自定义右侧数据信息end
             */

            isStandaloneMode: false,
            carWindow: null,
            carWindowContent: "",
            drawerVisible: false,
            drawerRightVisible: false,
            map: null,
            mapZoom: 13,
            loading: true,
            mapStyle: "normal",
            mapStyles: {
                normal: "normal",
                dark: "dark",
                light: "light",
                whitemap: "whitemap",
                grayscale: "grayscale",
                fresh: "fresh",
                techblue: "amap://styles/whitesmoke",
            },
            destination: {
                lng: 116.390074,
                lat: 39.898063,
            },
            websocket: null, // WebSocket实例
            trainLocationList: {}, // 车辆位置列表
            locationViewData: null, // 位置查看数据 { user: {}, order: {}, params: { userNo, workNo } }
            socketCar: {},
            socketPerson: {},
            personnelHistoryList: [], // 人员信息历史列表
            personTrackData: null, // 人员轨迹数据
            apiDataDrawn: {}, // 标记每辆车的接口数据是否绘制完成 { trainNo: boolean }
            websocketBuffer: {}, // 缓冲 WebSocket 数据 { trainNo: [] }
            isFullscreen: false,
            trainListParams: [], //设备车辆台账
            getWorkEquLists: [], //车上物资信息

            // 添加定时器相关变量
            getLocation: null, // 车辆位置定时器
            pollingInterval: 10000, // 轮询间隔(毫秒)，可根据需要调整
        };
    },
    props: {
        looDetails: {
            type: String,
            default: "",
        },
    },

    watch: {
        // drawerVisible(newVal) {
        //     if (!newVal) {
        //         this.drawerRightVisible = false;
        //     }
        // },
    },
    computed: {
        carList() {
            // realtime 模式：合并初始数据和实时数据

            const result = {};

            // 先添加初始数据（trainLocationList）
            Object.entries(this.trainLocationList).forEach(([key, value]) => {
                result[key] = Array.isArray(value) ? [...value] : value;
            });

            // 再添加实时数据（socketCar）
            Object.entries(this.socketCar).forEach(([key, value]) => {
                if (result[key] && Array.isArray(result[key]) && Array.isArray(value)) {
                    // 如果都是数组，则合并（追加到末尾）
                    result[key] = [...result[key], ...value];
                } else if (!result[key]) {
                    // 如果不存在，则直接赋值
                    result[key] = value;
                }
            });

            console.log("realtime 模式，carList 结构:", result);
            return result;
        },
    },
    mounted() {
        // 检测是否为独立模式
        this.isStandaloneMode = this.$route.path.includes("/standalone/");
        // 获取车辆位置列表数据
        this.fetchTrainLocations();

        // 延迟初始化地图，确保DOM完全加载
        this.$nextTick(() => {
            setTimeout(() => {
                this.initMap();
            }, 100);
        });
        document.addEventListener("fullscreenchange", this.handleFullscreenChange);
    },
    beforeDestroy() {
        document.removeEventListener("fullscreenchange", this.handleFullscreenChange);
        if (document.fullscreenElement) {
            const exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;
            if (exitFullscreen) {
                const result = exitFullscreen.call(document);
                if (result && typeof result.then === "function") {
                    result.catch(() => {});
                }
            }
        }
        // 清理地图实例
        if (this.map) {
            this.map.destroy();
        }

        // 关闭WebSocket连接
        if (this.websocket) {
            this.websocket.close();
        }
    },
    methods: {
        //事件信息面板任务信息数据改变的回调
        updateCurrentInfo(e) {
            this.currentChooseWorkInfo = e;
            //第二步骤需要根据编号获取车辆设备信息
            this.getWorkEquLists = [];
            this.drawerRightVisible = false;
            // if (e.workNo) {
            //     this.updateRightInfo(e);
            // }
            //第三步处理人员信息
            if (e.workNo) {
                this.fetchWorkNoGetUserList(e.workNo);
            }
        },

        //根据选中的任务编号获取作业人员的列表数据
        async fetchWorkNoGetUserList(workNo) {
            const userList = await getWorkOrderUserByWorkNo(workNo);
            if (userList.code == 200) {
                this.currentChooseWorkUserList = userList.data;
                const personnelData = userList.data.map(user => ({
                    id: user.id,
                    userNo: user.userNo,
                    workNo: workNo,
                    name: user.userName,
                    longitude: user.longitude ? parseFloat(user.longitude) : null,
                    latitude: user.latitude ? parseFloat(user.latitude) : null,
                    telephone: user.telephone || "",
                    online: user.status === "1", // status === '1' 表示在线
                }));

                this.personnelHistoryList = personnelData;
            }
        },
        async updateRightInfo(order) {
            if (!order.workNo || !order.trainNo) {
                return false;
            }
            const res = await getWorkEquList({
                workNo: order.workNo,
                carNo: order.trainNo,
            });
            if (res.code == 200) {
                const groupedData = {};
                const orderTrainList = order.trainNo.split(",").filter(trainNo => trainNo.trim() !== "") || [];
                // 先按车号分组
                res.data.forEach(item => {
                    const carNo = item.carNo || ""; // 处理 carNo 为空的情况
                    if (!groupedData[carNo]) {
                        groupedData[carNo] = {
                            carNo: carNo,
                            children: [],
                        };
                    }
                    groupedData[carNo].children.push(item);
                });
                // 按照 orderTrainList 的顺序组装数据，确保所有车号都存在
                const orderedData = [];
                orderTrainList.forEach(trainNo => {
                    const trimmedTrainNo = trainNo.trim();
                    if (groupedData[trimmedTrainNo]) {
                        // 如果有匹配的数据，使用实际数据
                        orderedData.push(groupedData[trimmedTrainNo]);
                    } else {
                        // 如果没有匹配的数据，创建空的车辆对象
                        orderedData.push({
                            carNo: trimmedTrainNo,
                            children: [],
                        });
                    }
                });

                // 处理不在 orderTrainList 中的车辆数据（额外的车辆数据）
                Object.keys(groupedData).forEach(carNo => {
                    const isInOrderList = orderTrainList.some(trainNo => trainNo.trim() === carNo);
                    if (!isInOrderList) {
                        orderedData.push(groupedData[carNo]);
                    }
                });
                this.getWorkEquLists = orderedData;
                this.drawerRightVisible = true;
            }
        },

        //事件信息面板是否展开
        toggleDrawer() {
            this.drawerVisible = !this.drawerVisible;
            if (this.drawerVisible) {
                this.$refs.DrawerPanel.fetchWorkOrderList();
            }
        },
        //全屏切换
        toggleFullscreen() {
            const appMain = document.querySelector(".app-main");
            if (!appMain) {
                return;
            }

            if (!document.fullscreenElement) {
                const requestFullscreen = appMain.requestFullscreen || appMain.webkitRequestFullscreen || appMain.mozRequestFullScreen || appMain.msRequestFullscreen;

                if (requestFullscreen) {
                    Promise.resolve(requestFullscreen.call(appMain)).catch(error => {
                        console.error("进入全屏失败:", error);
                    });
                }
            } else {
                const exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;

                if (exitFullscreen) {
                    Promise.resolve(exitFullscreen.call(document)).catch(error => {
                        console.error("退出全屏失败:", error);
                    });
                }
            }
        },
        handleFullscreenChange() {
            this.isFullscreen = Boolean(document.fullscreenElement);
            this.$nextTick(() => {
                if (this.map) {
                    this.map.resize();
                }
            });
        },

        //查看详情得时候 调用方法
        getCustfetchTrainLocations(workNo) {
            this.handleALlTrain(workNo);
            //初始化获取所有作业人员信息
            this.fetchWorkNoGetUserList();
        },
        // 获取车辆位置列表数据
        async fetchTrainLocations() {
            // 获取查询参数，例如 /emergency-monitor?workNo=123&taskId=456
            const workNo = this.$route.query.workNo || "";

            if (workNo) {
                // 获取 emergency-monitor 页面的查询参数
                this.handleALlTrain(workNo);
            } else if (this.looDetails.workNo) {
                this.handleALlTrain(this.looDetails.workNo);
            } else {
                // 获取 emergency-monitor 页面的查询参数
                this.handleALlTrain("");
            }

            console.log("获取到的所有的作业人员信息");
            this.fetchWorkNoGetUserList("JY20251201-001");
        },

        //全局初始化方法
        handleALlTrain(workNo) {
            if (workNo) {
                getWorkOrderList({
                    workNo: workNo,
                }).then(response => {
                    if (response.code == 200 && response.rows) {
                        this.getTbLocationTrainList({
                            trainNo: response.rows[0].trainNo,
                        });
                    }
                });
            } else {
                this.getTbLocationTrainList({ trainNo: "" });
                // 初始化WebSocket连接
                this.initWebSocket();
            }
            this.getTbLocationTrainList();
        },

        getTbLocationTrainList(params) {
            tbLocationTrainList(params)
                .then(response => {
                    if (response.code === 200) {
                        this.trainLocationList = response.data;
                        // 循环Object.values，如果value不是空数组，取第一个元素的trainNo赋值给carWindowContent
                        for (const value of Object.values(this.trainLocationList)) {
                            if (value && value.length > 0) {
                                this.carWindowContent = value[0].trainNo;
                                break;
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error("请求失败:", error);
                });
        },

        // 初始化WebSocket连接
        initWebSocket() {
            //暂时先注释这个定时器信息
            this.getLocation = setInterval(() => {
                this.fetchRealtimeTrainLocations();
            }, this.pollingInterval);
            //   // 创建WebSocket实例
            //   this.websocket = new WebSocketService('ws://123.138.45.195:9027/websocket/train_inner')
            //   // 设置回调函数
            //   this.websocket.setOnOpen((event) => {
            //     console.log('WebSocket连接成功')
            //     // 可以在这里发送初始化消息
            //     this.websocket.send({
            //       type: 'init',
            //       message: '客户端已连接'
            //     })
            //   })
            //   this.websocket.setOnMessage((data, event) => {
            //     // 处理接收到的消息
            //     this.handleWebSocketMessage(data)
            //   })
            //   this.websocket.setOnClose((event) => {
            //     console.log('WebSocket连接关闭')
            //   })
            //   this.websocket.setOnError((event) => {
            //     console.error('WebSocket错误:', event)
            //   })
            //   // 连接WebSocket
            //   this.websocket.connect()
        },

        async fetchRealtimeTrainLocations() {
            const locations = await getLocationQuertz();
            if (locations.code == 200 && locations.data) {
                this.handleWebSocketMessage(locations.data);
            }
        },
        // 处理WebSocket消息
        handleWebSocketMessage(data) {
            // 根据消息类型处理不同的业务逻辑
            if (data.tarin) {
                // 创建以trainNo为键的新对象
                const transformedData = {};
                // 如果data.tarin是数组
                if (Array.isArray(data.tarin)) {
                    data.tarin.forEach(item => {
                        if (item && item.trainNo) {
                            transformedData[item.trainNo] = item;
                        }
                    });
                }
                // 如果data.tarin是对象
                else if (typeof data.tarin === "object" && data.tarin !== null) {
                    Object.values(data.tarin).forEach(item => {
                        if (item && item.trainNo) {
                            transformedData[item.trainNo] = item;
                        }
                    });
                }
                this.updateVehiclePosition(transformedData);
            }
            if (data.user) {
                data.user.forEach(item => {
                    if (item && item.userNo) {
                        this.updateWorkerPosition(item);
                    }
                });
            }

            if (data.workOrder) {
            }
        },

        // 更新车辆位置
        updateVehiclePosition(payload) {
            Object.entries(payload).forEach(([key, value]) => {
                // 如果接口数据还没绘制完成，放入缓冲区
                if (!this.apiDataDrawn[key]) {
                    if (this.websocketBuffer[key]) {
                        this.websocketBuffer[key].push(value);
                    } else {
                        this.$set(this.websocketBuffer, key, [value]);
                    }
                } else {
                    // 接口数据已绘制完成，直接追加到 socketCar
                    if (this.socketCar[key]) {
                        this.socketCar[key].push(value);
                    } else {
                        this.$set(this.socketCar, key, [value]);
                    }
                }
            });
        },

        // 处理车辆绘制完成事件
        handleCarDrawComplete(trainNo) {
            // 标记接口数据已绘制完成
            this.$set(this.apiDataDrawn, trainNo, true);
            // 将缓冲区的 WebSocket 数据追加到 socketCar
            if (this.websocketBuffer[trainNo]?.length > 0) {
                this.$set(this.socketCar, trainNo, [...this.websocketBuffer[trainNo]]);
                // 清空缓冲区
                this.$set(this.websocketBuffer, trainNo, []);
            }
        },

        // 更新工作人员位置
        updateWorkerPosition(payload) {
            // 根据 id 匹配 personnelHistoryList 中的数据，更新经纬度
            if (payload && payload.userNo) {
                const workerIndex = this.personnelHistoryList.findIndex(worker => worker.userNo === payload.userNo);
                if (workerIndex !== -1) {
                    // 使用 $set 确保 Vue 能追踪属性的变化
                    this.$set(this.personnelHistoryList, workerIndex, {
                        ...this.personnelHistoryList[workerIndex],
                        longitude: parseFloat(payload.longitude),
                        latitude: parseFloat(payload.latitude),
                    });
                    console.log("工作人员位置已更新:", this.personnelHistoryList[workerIndex]);
                }
            }
        },

        // 更新任务信息
        updateTaskInfo(payload) {
            // 这里可以处理任务相关信息更新
            console.log("更新任务信息:", payload);
        },

        initMap() {
            if (!document.getElementById("map")) {
                console.error("地图容器未找到");
                return;
            }

            this.map = new AMap.Map("map", {
                zoom: this.mapZoom,
                center: [this.destination.lng, this.destination.lat],
                view: new AMap.View2D({}),
                lang: "zh_cn",
                mapStyle: this.mapStyles[this.mapStyle],
            });

            // 创建信息展示框
            this.carWindow = new AMap.InfoWindow({
                offset: new AMap.Pixel(6, -25),
                content: "",
            });

            this.map.on("complete", () => {
                this.loading = false;
            });

            if (this.map.readyState && this.map.readyState === "complete") {
                this.loading = false;
            }

            this.createDestinationMarker();
        },

        createDestinationMarker() {
            const destinationMarker = new AMap.Marker({
                map: this.map,
                position: [this.destination.lng, this.destination.lat],
                icon: new AMap.Icon({
                    size: new AMap.Size(32, 32),
                    image: "",
                    imageSize: new AMap.Size(32, 32),
                }),
                offset: new AMap.Pixel(-16, -16),
                title: "终点",
            });

            const destinationWindow = new AMap.InfoWindow({
                offset: new AMap.Pixel(0, -30),
                content: '<div class="destination-info">终点</div>',
            });

            destinationMarker.on("click", () => {
                destinationWindow.open(this.map, destinationMarker.getPosition());
            });
        },

        // 更新位置查看数据
        updateLocationViewData(data) {
            if (data) {
                // 打开时或获取到响应数据时，存储数据
                this.locationViewData = data;
                this.personTrackData = data; // 同时设置轨迹数据
                data.order = this.currentChooseWorkInfo;
            } else {
                // 关闭时，清空数据
                this.locationViewData = null;
                this.personTrackData = null; // 清空轨迹数据
            }
        },
        // 更新人员历史列表
        updatePersonnelHistory(data) {
            this.personnelHistoryList = data;
        },
        async drawerRightVisibleChange() {
            const trainList = await TbEquTrainList();
            if (trainList.code == 200) {
                this.trainListParams = trainList.rows;
            }
            this.drawerRightVisible = !this.drawerRightVisible;
        },
    },
};
</script>

<style>
.map-container {
    position: relative;
}

.left-info {
    position: absolute;
    top: 0;
    left: 0;

    height: 100%;
}

.right-info {
    position: absolute;
    top: 0;
    right: 0;

    height: 100%;
}

.map-container {
    position: relative;
}

.tech-blue-container {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #1a2a6c, #2a4b9b, #3a6cb0);
    padding: 20px;
    box-sizing: border-box;
    position: relative;
}

.map-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 15px;
    background: rgba(0, 25, 50, 0.7);
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}

.map-title {
    color: #4fc3f7;
    font-size: 24px;
    font-weight: 600;
    margin: 0;
    text-shadow: 0 0 10px rgba(79, 195, 247, 0.5);
}

.fullscreen-btn {
    padding: 8px 16px;
    background: rgba(0, 50, 100, 0.6);
    color: #bbdefb;
    border: 1px solid #4fc3f7;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.fullscreen-btn:hover {
    background: rgba(33, 150, 243, 0.6);
    color: #ffffff;
}

.style-btn {
    padding: 8px 15px;
    background: rgba(0, 50, 100, 0.6);
    color: #bbdefb;
    border: 1px solid #4fc3f7;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.style-btn:hover {
    background: rgba(33, 150, 243, 0.8);
    color: white;
    box-shadow: 0 0 10px rgba(33, 150, 243, 0.5);
}

.tech-map {
    width: 100%;
    height: calc(100vh - 130px);
    border-radius: 10px;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.4);
    border: 1px solid #4fc3f7;
    overflow: hidden;
    transition: opacity 0.3s ease;
}

.tech-map.map-hidden {
    opacity: 0;
}

/* 科技感loading样式 */
.tech-loading {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(10, 25, 47, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    border-radius: 10px;
}

.loading-content {
    text-align: center;
}

.loading-spinner {
    width: 60px;
    height: 60px;
    border: 4px solid rgba(2, 119, 189, 0.3);
    border-top: 4px solid #0277bd;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 20px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

.loading-text {
    color: #4fc3f7;
    font-size: 18px;
    font-weight: 500;
    text-shadow: 0 0 10px rgba(79, 195, 247, 0.7);
}

/* 添加脉冲效果 */
.loading-spinner::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border: 4px solid transparent;
    border-top-color: #4fc3f7;
    animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
    0% {
        transform: scale(0.8);
        opacity: 0.7;
    }
    50% {
        transform: scale(1.2);
        opacity: 0.3;
    }
    100% {
        transform: scale(0.8);
        opacity: 0.7;
    }
}

/* 弹窗动画效果 */
.amap-info-content {
    background: transparent !important;
    padding: 0 !important;
    max-width: none !important;
    border: none !important;
    box-shadow: none !important;
}

.amap-info-sharp {
    transform: perspective(1000px) rotateX(5deg);
    transition: transform 0.3s ease;
    animation: popup 0.4s ease-out;
}

.amap-info-sharp:hover {
    transform: perspective(1000px) rotateX(0deg);
}

@keyframes popup {
    0% {
        opacity: 0;
        transform: scale(0.8) translateY(20px);
    }
    100% {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
}

/* 终点信息样式 */
.destination-info {
    background: linear-gradient(145deg, #0c1e3e, #1a3a6a);
    border-radius: 8px;
    padding: 10px 15px;
    color: #ff5252;
    font-weight: bold;
    border: 1px solid #ff5252;
    box-shadow: 0 0 10px rgba(255, 82, 82, 0.5);
    text-align: center;
}
</style>
